<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检索" prop="search">
        <el-input v-model="queryParams.search" placeholder="请输入检索信息" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="选择类型" prop="recordType">
        <el-select v-model="queryParams.recordType" placeholder="选择类型">
          <el-option label="成品" value="1"></el-option>
          <el-option label="原料" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="节点类型" prop="parentId">
        <el-select v-model="queryParams.parentId" placeholder="节点类型">
          <el-option label="根节点" value="0"></el-option>
          <el-option label="二级节点" value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="规格" prop="recordSize">
        <el-select v-model="queryParams.recordSize" placeholder="规格">
          <el-option label="小型" value="1"></el-option>
          <el-option label="中型" value="2"></el-option>
          <el-option label="大型" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="供应商" prop="providerId">
        <el-select v-model="queryParams.providerId" placeholder="请选择供应商">
          <el-option v-for="item in providerList" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['wms:goods:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['wms:goods:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['wms:goods:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物料编码" align="center" prop="recordId" width="180" />
      <el-table-column label="商品" align="center" prop="goodsName" />
      <el-table-column label="物料型号" align="center" prop="recordShape">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.recordShape == '0'">
            物料
          </el-tag>
          <el-tag effect="dark" type="info" v-else-if="scope.row.recordShape == '1'">
            原料
          </el-tag>
          <el-tag effect="dark" v-else>
            暂无
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="物料类型" align="center" prop="recordType">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.recordType == '0'">
            物料
          </el-tag>
          <el-tag effect="dark" type="info" v-else-if="scope.row.recordType == '1'">
            原料
          </el-tag>
          <el-tag effect="dark" v-else>
            暂无
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="规格" align="center" prop="recordSize">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.recordSize == '1'">
            小
          </el-tag>
          <el-tag effect="dark" type="info" v-else-if="scope.row.recordSize == '2'">
            中
          </el-tag>
          <el-tag effect="dark" v-else-if="scope.row.recordSize == '3'">
            大
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="providerName" />
      <el-table-column label="图片" align="center" prop="goodsImg">
        <template slot-scope="scope">
          <el-image :src="scope.row.goodsImg" fit="cover" style=" width:50; height:50;">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="goodsPrice">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.goodsPrice != 0">
            {{ scope.row.goodsPrice }}
          </el-tag>
          <el-tag effect="dark" type="info" v-else>
            零元购
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="库存" align="center" prop="goodsNum" />
      <el-table-column label="类型" align="center" prop="recordType">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.recordType == '0'">
            成品
          </el-tag>
          <el-tag effect="dark" type="info" v-else-if="scope.row.recordType == '1'">
            原料
          </el-tag>
          <el-tag effect="dark" v-else>
            暂无
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="所属上级" align="center" prop="parentName">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.parentId == 0">
            顶级分类
          </el-tag>
          <el-tag effect="dark" type="info" v-else-if="scope.row.recordName != null">
            {{ scope.row.recordName }}
          </el-tag>
          <el-tag effect="dark" v-else>
            暂无
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="goodsStatus">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.goodsStatus" active-value="0" inactive-value="1"
            @change="handleStatusChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" width="120">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.createBy != null">
            {{ scope.row.createBy }}
          </el-tag>
          <el-tag effect="dark" type="info" v-else>
            暂无创建人
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建日期" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.createTime != null">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </el-tag>
          <el-tag effect="dark" type="info" v-else>
            暂无日期
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:goods:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['wms:goods:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物料编码" prop="recordId">
          <el-input v-model="form.recordId" placeholder="请输入物料编码" :disabled="form.id != null" />
        </el-form-item>
        <el-form-item label="物料名称" prop="goodsName" v-if="form.flag != '0'">
          <el-input v-model="form.goodsName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="父类名" prop="goodsName" v-if="form.flag == '0'">
          <el-input v-model="form.goodsName" placeholder="请输入父类名" />
        </el-form-item>

        <el-form-item label="选择类型" prop="recordType">
          <el-select v-model="form.recordType" placeholder="选择类型">
            <el-option label="成品" value="1"></el-option>
            <el-option label="原料" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物料型号" prop="recordShape" v-if="form.flag != '0'">
          <el-select v-model="form.recordShape" placeholder="请输入物料型号">
            <el-option label="成品" value="1"></el-option>
            <el-option label="原料" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格" prop="recordSize" v-if="form.flag != '0'">
          <el-select v-model="form.recordSize" placeholder="规格">
            <el-option label="小型" value="1"></el-option>
            <el-option label="中型" value="2"></el-option>
            <el-option label="大型" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库" prop="wareName" v-if="form.flag != '0'">
          <el-cascader :disabled="form.id != null" v-model="form.wareName" :options="wareList" :props="props"
            clearable></el-cascader>
        </el-form-item>
        <el-form-item label="生产单位" prop="productName" v-if="form.flag != '0'">
          <el-cascader :disabled="form.id != null" v-model="form.productName" :options="productList" :props="props1"
            clearable></el-cascader>
        </el-form-item>
        <el-form-item label="供应商" prop="providerId" v-if="form.flag != '0'">
          <el-select v-model="form.providerId" placeholder="请选择供应商">
            <el-option :disabled="form.id != null" v-for="item in providerList" :label="item.name" :value="item.id"
              :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物料价格" prop="recordPrice" v-if="form.flag != '0'">
          <el-input-number v-model="form.recordPrice" :min="0" :max="999999" label="请输入物料价格"></el-input-number>
        </el-form-item>
        <el-form-item label="父类">
          <el-radio-group v-model="form.flag" :disabled="form.id != null">
            <el-radio :label="'1'">默认</el-radio>
            <el-radio :label="'0'" checked>根节点</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属分类 " prop="parentId" v-if="form.flag != '0'">
          <el-select v-model="form.parentId" placeholder="请选择所属分类">
            <el-option v-for="item in RecordList" :label="item.goodsName" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" @change="handleChange" :min="0" :max="10" label="请选择排序"></el-input-number>
        </el-form-item>
        <el-form-item label="库存" prop="goodsNum" v-if="form.goodsNum != null">
          <el-input-number v-model="form.goodsNum" :min="0" :max="99999" label="库存" :disabled="true">
          </el-input-number>
        </el-form-item>
        <el-form-item label="总数" prop="goodsTotal" v-if="form.flag != '0'">
          <el-input-number v-model="form.goodsTotal" @change="handleChangeGoodsTotal" :min="0" :max="99999"
            label="请输入商品总数">
          </el-input-number>
        </el-form-item>

        <el-form-item label="图片" prop="goodsImg" v-if="form.flag != '0'">
          <el-upload class="upload-demo" v-model="form.goodsImg" action="/dev-api/wms/provider/upload"
            :on-success="handleSuccess" :file-list="fileList" list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRecordInfoList, changeGoodsStatus, listGoods, getGoods, delGoods, addGoods, updateGoods } from "@/api/wms/goods";
import { providerList } from "@/api/wms/provider"
import { getCascaderWare } from "@/api/wms/ware"
import { getProductTreeNode } from "@/api/wms/product"
export default {
  name: "Goods",
  data () {
    return {
      //仓库
      wareList: [],
      props: {
        value: 'id',
        label: 'wareName',
        children: "children"
      },
      // 生产厂家
      productList: [],
      props1: {
        value: 'id',
        label: 'name',
        children: "children"
      },
      // 全部档案
      RecordList: [],
      // 供应商
      providerList: [],
      fileList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品信息表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
        recordPrice: '0',
        sort: '1',
        flag: '1',

      },
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "分类不能为空", trigger: "blur" }
        ],
        recordType: [
          { required: true, message: "选择分类不能为空", trigger: "blur" }
        ],
        recordName: [
          { required: true, message: "物料名称不能为空", trigger: "blur" }
        ],
        providerId: [
          { required: true, message: "供应商不能为空", trigger: "blur" }
        ],
        goodsName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        goodsType: [
          { required: true, message: "商品类型", trigger: "change" }
        ],
        goodsImg: [
          { required: true, message: "商品图片不能为空", trigger: "blur" }
        ],


      }
    };
  },
  created () {
    this.getList();
    this.getproviderList();
    this.getWareList(),
      this.getProductTreeList()
  },
  methods: {
    // 格式化数据，递归将空的children置为undefined
    formatData (data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.formatData(data[i].children)
        }
      }
      return data;
    },
    // 获取仓库信息
    getWareList () {
      getCascaderWare().then(res => {
        this.wareList = this.formatData(res.data)
      })
    },
    // 获取生产单位树形结构
    getProductTreeList () {
      getProductTreeNode().then(res => {
        this.productList = res.data
      })
    },
    handleChange (value) {
      this.form.sort = value
    },
    // 获取全部档案
    getRecordList () {
      getRecordInfoList().then(res => {
        this.RecordList = res.data;
      })
    },
    // 所有供应商信息
    getproviderList () {
      providerList().then(res => {
        this.providerList = res.data
      })
    },
    handleChangeGoodsPrice (value) {
      this.form.goodsPrice = value
    },
    handleChangeGoodsTotal (value) {
      this.form.goodsTotal = value
    },

    // 上传成功 回调函数
    handleSuccess (response, file, fileList) {
      console.log(response);
      var data = {
        name: response.name,
        url: response.file
      }
      this.fileList.push(data)
      this.form.goodsImg = response.file
    },
    // 修改商品状态
    handleStatusChange (row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + row.goodsName + '"吗？').then(function () {
        return changeGoodsStatus(row.id, row.goodsStatus);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
        this.getList()
      }).catch(function () {
        row.goodsStatus = row.goodsStatus === "0" ? "1" : "0";
      });
    },
    /** 查询商品信息列表 */
    getList () {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.fileList = []
      this.form = {
        goodsPrice: '0',
        goodsTotal: '1',
        recordPrice: '0',
        sort: '1',
        flag: '1'

      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.getProductTreeList()
      this.getWareList()
      this.reset();
      this.getRecordList();
      this.open = true;
      this.title = "添加商品信息";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      this.getRecordList();
      const id = row.id || this.ids
      getGoods(id).then(response => {
        this.form = response.data;
        if (response.data.goodsImg != null) {
          this.fileList.push({
            name: response.data.goodsImg,
            url: response.data.goodsImg
          })
        }
        if (this.form.parentId == '0') {
          this.form.flag = '0'
        } else {
          this.form.flag = '1'
        }
        this.open = true;
        this.title = "修改商品信息";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          addGoods(this.form).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品信息编号为"' + ids + '"的数据项？').then(function () {
        return delGoods(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

  }
};
</script>
<style lang="scss" scoped>
.el-image {
  border-radius: 5px;
  background-color: #ebeef5;
  box-shadow: 0 0 5px 1px #ccc;

  ::v-deep .el-image__inner {
    transition: all 0.3s;
    cursor: pointer;

    &:hover {
      transform: scale(1.2);
    }
  }

  ::v-deep .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    color: #909399;
    font-size: 30px;
  }
}</style>